package com.leadnews.controller.mail;

import com.leadnews.mapper.UserMapper;
import com.leadnews.pojo.User;
import com.leadnews.vo.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@RestController
@RequestMapping("/sendMail@1")
@Slf4j
@CrossOrigin(origins = "*",maxAge = 3600)
public class MailController {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    UserMapper userMapper;
    @RequestMapping("/send")
    public ResponseResult sendMail(String mail) {
        ResponseResult result = new ResponseResult();
        User user=userMapper.findByMail(mail);
        if (user!=null){
            result.setCode(300);
            result.setErrorMessage("邮箱已存在，请更换");
            return result;
        }
        SimpleMailMessage message = new SimpleMailMessage();
        Random random = new Random();
        int i = random.nextInt(899999) + 100000;
        message.setFrom("zp1772108@163.com");
        message.setTo(mail);
        message.setSubject("frontvue系统验证码");
        message.setText("邮箱验证码为: " + i+" ,请勿发送给他人");
        try {
            mailSender.send(message);
            result.setCode(200);
            result.setData(i);
            log.info("验证码邮件已发送。");
        } catch (Exception e) {
            log.error("发送验证码邮件时发生异常了！", e);
            result.setData(0);
        }

        return result;
    }
    @RequestMapping("/sendlogin")
    public ResponseResult sendlogin(String mail) {
        ResponseResult result = new ResponseResult();
        User user=userMapper.findByMail(mail);
        if (user==null){
            result.setCode(300);
            result.setErrorMessage("邮箱不存在，请先注册");
            return result;
        }
        SimpleMailMessage message = new SimpleMailMessage();
        Random random = new Random();
        int i = random.nextInt(899999) + 100000;
        message.setFrom("zp1772108@163.com");
        message.setTo(mail);
        message.setSubject("frontvue系统验证码");
        message.setText("邮箱验证码为: " + i+" ,请勿发送给他人");
        try {
            mailSender.send(message);
            result.setCode(200);
            result.setData(i);
            log.info("验证码邮件已发送。");
        } catch (Exception e) {
            log.error("发送验证码邮件时发生异常了！", e);
            result.setData(0);
        }

        return result;
    }
}